<template>
  <div>
    <BasicModal @register="registerModal" :helpMessage="['查看帮助']" v-bind="$attrs">
      <BasicForm @register="editRegisterFrom">
        <template #addRuleStepSlot>
          <!--步骤进度-->
          <Steps :current="current">
            <Step title="基本设置" />
            <Step title="告警触发设置" />
          </Steps>
        </template>
        <template #templateSelectSlot>
          <div style="display: flex">
            <Select
              show-search
              :show-arrow="false"
              v-model:value="selectTemplate"
              @focus="getSelectList"
            >
              <SelectOption v-for="(item, index) in selectOptions" :key="index" :value="item.name">
                {{ item.name }}
                <Tag
                  :bordered="false"
                  color="blue"
                  v-for="(mItem, index) in item.configuration.deliveryMethodsTemplates"
                  :key="index"
                  >{{ mItem.method }}</Tag
                >
              </SelectOption>
            </Select>
          </div>
        </template>
        <template #upgradingChainSlot>
          <UpgradingChainModal @first-recipient="getFirstRecipient" @time-flag="getTimeFlag" />
        </template>
        <template #addRuleFilterSlot>
          <div class="add-rule-filter-box">
            <InputList
              input-title="告警类型列表"
              @get-input-data-list="getInputDataList"
              v-show="
                triggerFlag === 'ALARM' ||
                triggerFlag === 'ALARM_COMMENT' ||
                triggerFlag === 'ALARM_ASSIGNMENT'
              "
            />
            <div
              v-show="
                triggerFlag === 'ALARM' ||
                triggerFlag === 'ALARM_COMMENT' ||
                triggerFlag === 'ALARM_ASSIGNMENT'
              "
            >
              <span>警报严重性列表</span>
              <FormItem>
                <Select
                  style="width: 100%"
                  show-search
                  mode="multiple"
                  placeholder="任何严重程度"
                  v-model:value="selectSeriousAlarm"
                  :options="seriousAlarmSelectList"
                  :show-arrow="true"
                />
              </FormItem>
            </div>
            <FormItem v-show="triggerFlag === 'ENTITY_ACTION'">
              <Select
                style="width: 100%"
                show-search
                mode="multiple"
                placeholder="选择实体操作类型"
                :options="entityTypeSelectList"
                :show-arrow="true"
              />
            </FormItem>
            <div v-show="triggerFlag === 'ALARM_COMMENT' || triggerFlag === 'ALARM_ASSIGNMENT'">
              <span
                v-show="
                  triggerFlag === 'ALARM' ||
                  triggerFlag === 'ALARM_COMMENT' ||
                  triggerFlag === 'ALARM_ASSIGNMENT'
                "
                >告警状态列表</span
              >
              <FormItem>
                <Select
                  style="width: 100%"
                  show-search
                  mode="multiple"
                  placeholder="任何状态"
                  :options="ruleAlarmSelectList"
                  :show-arrow="true"
                />
              </FormItem>
            </div>
            <FormItem
              v-for="(item, index) in entityOperationSelectList"
              :key="index"
              v-show="triggerFlag === 'ENTITY_ACTION'"
            >
              <Switch v-model:checked="item.switchFlag" checked-children="√" />
              <span>{{ item.title }}</span>
            </FormItem>
          </div>
        </template>
        <template #ruleEngineFilterSlot>
          <div class="add-rule-filter-box">
            <div>
              <span>规则链库</span>
              <FormItem>
                <Select
                  style="width: 100%"
                  show-search
                  mode="multiple"
                  placeholder="选择规则链库"
                  :options="ruleChainLibrarySelectList"
                  :show-arrow="true"
                />
              </FormItem>
            </div>
            <div>
              <span>规则链事件</span>
              <FormItem>
                <Select
                  style="width: 100%"
                  show-search
                  mode="multiple"
                  placeholder="选择规则链事件"
                  :options="ruleChainEventsSelectList"
                  :show-arrow="true"
                />
              </FormItem>
            </div>
            <FormItem>
              <Switch v-model:checked="ruleChainFailure" checked-children="√" />
              <span>仅在规则链生命周期故障时通知</span>
            </FormItem>
          </div>
        </template>
        <template #ruleNodeFilterSlot>
          <div class="add-rule-filter-box">
            <FormItem>
              <Switch v-model:checked="ruleNodeEvents" checked-children="√" />
              <span>追踪规则节点事件</span>
            </FormItem>
            <div v-show="ruleNodeEvents">
              <div>
                <span>规则链事件</span>
                <FormItem>
                  <Select
                    style="width: 100%"
                    show-search
                    mode="multiple"
                    placeholder="选择规则链事件"
                    :options="ruleChainEventsSelectList"
                    :show-arrow="true"
                  />
                </FormItem>
              </div>
              <FormItem>
                <Switch v-model:checked="ruleNodeFailure" checked-children="√" />
                <span>仅在规则链生命周期故障时通知</span>
              </FormItem>
            </div>
          </div>
        </template>
        <template #noticeSwitchSlot>
          <FormItem v-for="(item, index) in noticeSelectList" :key="index">
            <Switch v-model:checked="item.switchFlag" checked-children="√" />
            <span>{{ item.title }}</span>
          </FormItem>
        </template>
        <template #typeButtonSlot>
          <div class="type-button">
            <Button
              class="mr-2"
              :type="typeButtonFlag === 'primary' ? 'primary' : 'ghost'"
              @click="deviceClick"
            >
              设备</Button
            >
            <Button
              class="mr-2"
              :type="typeButtonFlag === 'ghost' ? 'primary' : 'ghost'"
              @click="ConfigurationClick"
              >设备配置
            </Button>
          </div>
        </template>
      </BasicForm>
      <!--底部按钮-->
      <template #footer>
        <Button
          class="mr-2"
          type="primary"
          size="middle"
          @click="stepLastClick"
          v-show="current > 0"
          >后退</Button
        >
        <Button class="mr-2" type="primary" size="middle" @click="stepNextClick">{{
          okText
        }}</Button>
      </template>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { Button, Tag, Steps, Step, Select, SelectOption, FormItem, Switch } from 'ant-design-vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    seriousAlarmSelectList,
    notificationAlarmSelectList,
    notificationActivitySelectList,
    entityTypeSelectList,
    entityOperationSwitchList,
    ruleAlarmSelectList,
    noticeSwitchList,
    ruleChainLibrarySelectList,
    ruleChainEventsSelectList,
  } from '../data/notification.data';
  import { onMounted, ref, watch } from 'vue';
  import {
    getTargetsList,
    getTemplatesList,
    getTenantSelectList,
    getDeviceProfileInfosSelectList,
  } from '/@/api/thingsborad/notification/notification';
  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  import UpgradingChainModal from './UpgradingChainModal.vue';
  import InputList from '/@/components/thingsborad/sharedComponents/modules/InputList.vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  const emits = defineEmits(['closeFlag']);

  // eslint-disable-next-line vue/require-prop-types
  let selectTemplate = ref<any>();
  let selectSeriousAlarm = ref<any>();
  // 步骤条进度
  let current = ref(0);
  //规则收件人下拉列表数据
  let recipientSelectOptions = ref<any>([]);
  //筛选器文字提示
  let filterTextFlag = ref<string>('筛选器');
  //触发器标记
  let triggerFlag = ref<string>('');
  //仅在规则链生命周期故障时通知
  let ruleChainFailure = ref<boolean>(false);
  //追踪规则节点事件
  let ruleNodeEvents = ref<boolean>(false);
  let ruleNodeFailure = ref<boolean>(false);
  //表单初始化注册
  let editSchemas: FormSchema[] = [
    {
      field: 'addRuleStep',
      component: 'Input',
      slot: 'addRuleStepSlot',
      label: '',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'ruleName',
      component: 'Input',
      label: '规则名称',
      required: true,
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'enableName',
      component: 'Switch',
      label: '启用通知规则',
    },
    {
      show: (value) => {
        triggerFlag.value = value.model.addRuleTrigger;
        return current.value === 0;
      },
      field: 'addRuleTrigger',
      component: 'Select',
      label: '触发器',
    },
    {
      show: () => {
        return current.value === 0;
      },
      field: 'templateSelect',
      component: 'Input',
      slot: 'templateSelectSlot',
      label: '模板',
    },
    {
      show: (value) => {
        return value.model.addRuleTrigger === 'ALARM' && current.value === 0;
      },
      field: 'upgradingChain',
      component: 'Input',
      slot: 'upgradingChainSlot',
      label: '逐步升级链',
      colProps: {
        span: 24,
      },
    },
    {
      show: (value) => {
        return value.model.addRuleTrigger !== 'ALARM' && current.value === 0;
      },
      field: 'ruleRecipient',
      component: 'Select',
      label: '收件人',
      colProps: {
        span: 24,
      },
      componentProps: {
        mode: 'multiple',
        options: recipientSelectOptions.value,
      },
    },
    {
      show: () => {
        return (
          current.value === 1 &&
          (triggerFlag.value === 'ALARM' ||
            triggerFlag.value === 'ENTITY_ACTION' ||
            triggerFlag.value === 'ALARM_ASSIGNMENT' ||
            triggerFlag.value === 'ALARM_COMMENT')
        );
      },
      field: 'addRuleFilter',
      component: 'Input',
      label: filterTextFlag.value,
      slot: 'addRuleFilterSlot',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1 && triggerFlag.value === 'ALARM_COMMENT';
      },
      field: 'noticeSwitch',
      component: 'Switch',
      label: '',
      slot: 'noticeSwitchSlot',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1 && triggerFlag.value === 'RULE_ENGINE_LIFECYCLE_EVENT';
      },
      field: 'ruleEngineFilter',
      component: 'Switch',
      label: '规则引擎筛选器',
      slot: 'ruleEngineFilterSlot',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1 && triggerFlag.value === 'RULE_ENGINE_LIFECYCLE_EVENT';
      },
      field: 'ruleNodeFilter',
      component: 'Switch',
      label: '规则节点筛选器',
      slot: 'ruleNodeFilterSlot',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1 && triggerFlag.value === 'DEVICE_ACTIVITY';
      },
      field: 'typeButton',
      component: 'Input',
      label: '',
      slot: 'typeButtonSlot',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1 && triggerFlag.value === 'DEVICE_ACTIVITY';
      },
      field: 'deviceSelect',
      component: 'Select',
      label: '设备',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '如果该字段为空，则触发器将适用于所有设备。',
      },
    },
    {
      show: () => {
        return (
          current.value === 1 &&
          triggerFlag.value !== 'ALARM_COMMENT' &&
          triggerFlag.value !== 'ENTITY_ACTION' &&
          triggerFlag.value !== 'RULE_ENGINE_LIFECYCLE_EVENT'
        );
      },
      field: 'notificationConditionsSelect',
      component: 'Select',
      label: '通知条件',
      colProps: {
        span: 24,
      },
    },
    {
      show: () => {
        return current.value === 1;
      },
      field: 'addRuleDescribe',
      component: 'Input',
      label: '描述',
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '输入描述',
      },
    },
  ];
  //创建模板下拉
  let selectOptions = ref<any>([]);
  let inputDataList = ref<any>();
  let okText = ref<string>('下一步');
  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 50,
    page: 0,
    sortProperty: 'name',
    sortOrder: 'ASC',
    notificationType: 'ALARM',
  });

  //顶部
  let typeButtonFlag = ref<string>('primary');
  //设备下拉列表
  let deviceSelectList = ref<any>([]);
  let firstRecipient = ref<Array<any>>();
  let otherRecipient = ref<Array<any>>([
    {
      time: '',
      id: [],
    },
  ]);
  //
  let entityOperationSelectList = ref(entityOperationSwitchList);
  let noticeSelectList = ref(noticeSwitchList);
  //初始化
  onMounted(() => {
    setModalProps({
      showCancelBtn: false,
      showOkBtn: false,
      width: 800,
      loading: false,
      confirmLoading: false,
      ...modalStyleSetting,
    });
    //获取收件人下拉列表
    getRecipientSelectList(params.value);
    // 获取设备下拉
    getDeviceSelectList(params.value);
  });
  //组件通信 获取输入款数据
  function getInputDataList(dataList) {
    inputDataList.value = dataList;
  }
  //设备点击事件
  function deviceClick() {
    typeButtonFlag.value = 'primary';
  }
  //设备配置点击事件
  function ConfigurationClick() {
    typeButtonFlag.value = 'ghost';
  }

  //获取下拉数据
  async function getSelectList() {
    selectOptions.value = [];
    //请求参数
    let params = ref<notificationsParams>({
      pageSize: 10,
      page: 0,
      sortProperty: 'name',
      sortOrder: 'ASC',
      notificationTypes: 'ALARM',
    });
    let switchFlag;
    switch (triggerFlag.value) {
      case 'DEVICE_ACTIVITY':
        switchFlag = 'DEVICE_ACTIVITY';
        break;
      case 'ENTITY_ACTION':
        switchFlag = 'ENTITY_ACTION';
        break;
      case 'ALARM_COMMENT':
        switchFlag = 'ALARM_COMMENT';
        break;
      case 'ALARM_ASSIGNMENT':
        switchFlag = 'ALARM_ASSIGNMENT';
        break;
      case 'RULE_ENGINE_LIFECYCLE_EVENT':
        switchFlag = 'RULE_ENGINE_COMPONENT_LIFECYCLE_EVENT';
        break;
      case 'ALARM':
        switchFlag = 'ALARM';
        break;
    }
    params.value.notificationTypes = switchFlag;
    try {
      const templatesData = await getTemplatesList(params.value);

      //判空
      if (templatesData.data.length === 0) {
        return;
      }
      //分页数据
      templatesData.data.forEach((item) => {
        selectOptions.value.push(item);
      });
      // 根据需要处理数据并更新组件状态
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  const [editRegisterFrom, { updateSchema, validate, resetFields }] = useForm({
    layout: 'vertical',
    schemas: editSchemas,
    actionColOptions: {
      span: 24,
    },
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  watch(
    () => [triggerFlag.value, typeButtonFlag.value],
    ([nValTrigger, nValType]) => {
      if (nValTrigger === 'DEVICE_ACTIVITY') {
        updateSchema({
          field: 'notificationConditionsSelect',
          componentProps: {
            mode: 'multiple',
            options: notificationActivitySelectList,
          },
        });
      } else if (nValTrigger === 'ALARM') {
        updateSchema({
          field: 'notificationConditionsSelect',
          componentProps: {
            mode: 'multiple',
            options: notificationAlarmSelectList,
          },
        });
      }
      getDeviceSelectList(params.value);
      if (nValType === 'primary') {
        updateSchema({
          field: 'deviceSelect',
          component: 'Select',
          label: '设备',
          componentProps: {
            placeholder: '如果该字段为空，则触发器将适用于所有设备。',
            mode: 'multiple',
            options: deviceSelectList.value,
          },
        });
      } else {
        updateSchema({
          field: 'deviceSelect',
          component: 'Select',
          label: '设备配置',
          componentProps: {
            placeholder: '如果该字段为空，则触发器将适用于所有设备配置。',
            mode: 'multiple',
            options: deviceSelectList.value,
          },
        });
      }
    },
  );
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
    if (hasPermission('TENANT_ADMIN')) {
      updateSchema({
        field: 'addRuleTrigger',
        defaultValue: 'ALARM',
        componentProps: {
          options: [
            {
              label: '告警',
              value: 'ALARM',
            },
            {
              label: '设备活动',
              value: 'DEVICE_ACTIVITY',
            },
            {
              label: '实体操作',
              value: 'ENTITY_ACTION',
            },
            {
              label: '告警评论',
              value: 'ALARM_COMMENT',
            },
            {
              label: '告警分配',
              value: 'ALARM_ASSIGNMENT',
            },
            {
              label: '规则引擎生命周期事件',
              value: 'RULE_ENGINE_LIFECYCLE_EVENT',
            },
          ],
        },
      });
    }
    if (hasPermission('SYS_ADMIN')) {
      updateSchema({
        field: 'addRuleTrigger',
        defaultValue: 'ALARM',
        componentProps: {
          options: [
            {
              label: '实体限制',
              value: 'ALARM',
            },
            {
              label: 'API使用限制',
              value: 'DEVICE_ACTIVITY',
            },
            {
              label: '新的平台版本',
              value: 'ENTITY_ACTION',
            },
            {
              label: 'Exceeded rate limits',
              value: 'ALARM_COMMENT',
            },
          ],
        },
      });
    }

    updateSchema({
      field: 'deviceSelect',
      componentProps: {
        mode: 'multiple',
        options: deviceSelectList.value,
      },
    });
  });

  //获取
  async function getRecipientSelectList(params: notificationsParams) {
    recipientSelectOptions.value = [];
    try {
      const targetsData = await getTargetsList(params);
      //判空
      if (targetsData.data.length === 0) {
        return;
      }
      targetsData.data.forEach((item) => {
        recipientSelectOptions.value.push({
          value: item.id.id,
          label: item.name,
        });
      });
      // 根据需要处理数据并更新组件状态
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  //获取设备下拉列表
  async function getDeviceSelectList(params: notificationsParams) {
    deviceSelectList.value = [];
    if (hasPermission('SYS_ADMIN')) {
      return;
    }
    try {
      let tenantListData: any;
      if (typeButtonFlag.value === 'primary') {
        tenantListData = await getTenantSelectList(params);
      } else {
        tenantListData = await getDeviceProfileInfosSelectList(params);
      }
      //判空
      if (tenantListData.data.length === 0) {
        return;
      }
      tenantListData.data.forEach((item) => {
        deviceSelectList.value.push({
          value: item.id.id,
          label: item.name,
        });
      });
      // 根据需要处理数据并更新组件状态
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  //步骤进度下一步点击事件
  async function stepNextClick() {
    if (current.value === 1) {
      try {
        let validateValue = await validate();
        let templateIdFlag: any;
        selectOptions.value.forEach((item) => {
          if (item.name === selectTemplate.value) {
            templateIdFlag = item.id;
            return;
          }
        });

        let data: any = {
          name: validateValue.ruleName,
          enabled: validateValue.enableName,
          templateId: templateIdFlag,
          triggerType: validateValue.addRuleTrigger,
          recipientsConfig: {},
          triggerConfig: {},
          additionalConfig: {
            description: validateValue.addRuleDescribe,
          },
        };

        if ((validateValue.addRuleTrigger = 'ALARM')) {
          let alarmTypesFlag: any = [];
          if (inputDataList.value !== undefined) {
            inputDataList.value.forEach((item) => {
              alarmTypesFlag.push(item.text);
            });
          }
          data.recipientsConfig = {
            escalationTable: {
              '0': firstRecipient.value,
            },
            triggerType: validateValue.addRuleTrigger,
          };
          data.triggerConfig = {
            alarmTypes: alarmTypesFlag,
            alarmSeverities: selectSeriousAlarm.value,
            notifyOn: validateValue.notificationConditionsSelect,
            triggerType: validateValue.addRuleTrigger,
          };
          if (otherRecipient.value.length > 1) {
            otherRecipient.value.forEach((item, index) => {
              if (index !== 0) {
                data.recipientsConfig.escalationTable[item.time] = item.id;
              }
            });
          }
        }

        if ((validateValue.addRuleTrigger = 'DEVICE_ACTIVITY')) {
          data.recipientsConfig = {
            targets: ['a1a72d60-a49e-11ee-99f6-535103f50c3f'],
            triggerType: 'DEVICE_ACTIVITY',
          };
          data.triggerConfig = {
            devices: ['c33fa1b0-a52e-11ee-99f6-535103f50c3f'],
            notifyOn: ['INACTIVE'],
            triggerType: 'DEVICE_ACTIVITY',
          };
        }

        // await createRule(data);
        emits('closeFlag', true);
        otherRecipient.value = [
          {
            time: '',
            id: [],
          },
        ];
        resetFields();
        current.value = 0;
        closeModal();
      } catch (error) {}
    }
    if (current.value + 1 < 2) {
      current.value += 1;
    }
  }
  //步骤进度后退点击事件
  function stepLastClick() {
    current.value -= 1;
  }
  watch(
    () => current.value,
    (nVal) => {
      if (1 === nVal) {
        okText.value = '保存';
      } else {
        okText.value = '下一步';
      }
    },
  );
  function getFirstRecipient(value) {
    if (value.index === 0) {
      firstRecipient.value = value.value;
    } else {
      if (value.index >= otherRecipient.value.length) {
        otherRecipient.value.push({
          time: '',
          id: value.value,
        });
      } else {
        otherRecipient.value[value.index].id = value.value;
      }
    }
  }
  function getTimeFlag(value) {
    if (value.index >= otherRecipient.value.length) {
      otherRecipient.value.push({
        time: value.value,
        id: [],
      });
    } else {
      otherRecipient.value[value.index].time = value.value;
    }
  }
</script>

<style lang="less" scoped>
  .inbox-constant {
    display: flex;
    justify-content: space-between;
    span {
      width: 90%;
    }
    div {
      width: 10%;
      span {
        font-size: 12px;
        color: #707070;
        text-align: center;
      }
      .icon-box {
        align-items: center;
      }
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .inbox-button {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
  }
  .type-button {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
  }
  .inbox-button .ant-tag {
    margin-left: auto;
  }
  .add-rule-filter-box {
    border: 1px solid #666;
    border-radius: 5px;
    padding: 10px;
  }
</style>
